vector<int> spiralOrder(vector<vector<int> > &matrix)
{
    vector<int> result;
    if(matrix.empty())
        return result;
    int sx = 0;
    int sy = 0;
    int ex = matrix[0].size() - 1;
    int ey = matrix.size() - 1;
    while(true) {
        // From left to right
        for(int j = sx; j <= ex; ++j)
            result.push_back(matrix[sy][j]);
        if(++sy > ey)
            break;

        // From top to bottom
        for(int i = sy; i <= ey; ++i)
            result.push_back(matrix[i][ex]);
        if(sx > --ex)
            break;

        // From right to left
        for(int j = ex; j >= sx; --j)
            result.push_back(matrix[ey][j]);
        if(sy > --ey)
            break;

        // From bottom to top
        for(int i = ey; i >= sy; --i)
            result.push_back(matrix[i][sx]);
        if(++sx > ex)
            break;
    }
    return result;
}
